#include "LocalResourceHashTable.h"
//necessary
#include "main-tools.h"
#include "memory-tools.h"

//TODO testing
void initLocalResourceHashTable(PlocalResourceHashTable phashtable){
	*phashtable=NULL;
}

//TODO testing
PlocalResourceElement findLocalResourceInHashTable(PlocalResourceHashTable phashtable,const char* key){
	PlocalResourceHTCell result;
	HASH_FIND_STR(*phashtable,key,result);
	if (result==NULL){
		return NULL;
	}
	return result->localResource;
}

//TODO testing
void addLocalResourceInHashTable(PlocalResourceHashTable phashtable, PlocalResourceElement localresource){
	PlocalResourceHTCell pcell=initLocalResourceHTCell(localresource);
	HASH_ADD_KEYPTR(hh,*phashtable,pcell->key,strlen(pcell->key),pcell);
}

//TODO testing
void freeLocalResourceHashTable(PlocalResourceHashTable phashtable){
	PlocalResourceHTCell element;
	PlocalResourceHTCell tmp;

	HASH_ITER(hh,*phashtable,element,tmp){
		HASH_DEL(*phashtable,element);
		freeLocalResourceHTCell(element);
	}
}

//TODO testing
void generateDOTLocalResourceHashTable(FILE* f,PlocalResourceHashTable phashtable,int* nodenumber,int* htcell,int format){
	int items;
	int i;
	int tablenode=*nodenumber;
	int htcellnode;

	printTabs(f,format);	fprintf(f,"subgraph {\n");
	printTabs(f,format+1);	fprintf(f,"nodesep=0.05;");
	printTabs(f,format+1);	fprintf(f,"rankdir=\"LR\";\n");

	//generation of the node representing the hash table. This representation is not the real representation of the
	items=HASH_COUNT(*phashtable);
	printTabs(f,format+1);	fprintf(f,"table%04d [shape=\"record\" fillcolor=\"blue\" label=\"",tablenode);
	for (i=0;i<items;i++){
		fprintf(f,"<l%04d>|",i);
	}
	fprintf(f,"\"];\n");

	//generation of the nodes attached to the hash table
	LocalResourceHashTable tmp;
	for (tmp=*phashtable, i=0; tmp!=NULL; tmp=tmp->hh.next, i++){
		generateDOTLocalResourceHTCell(f,tmp,nodenumber,&htcellnode,format+1);
		fprintf(f,"\n");
		printTabs(f,format+1);	fprintf(f,"table%04d:l%04d -> n%04d;\n",tablenode,i,htcellnode);
	}
	printTabs(f,format);
	fprintf(f,"}\n");
}

